﻿/*
 * 版 本 v1.0
 * Copyright (c) 2013-2018 广州市同慧信息科技有限公司
 * 创建人：ftquan
 * 日 期：2017.04.18
 * 描 述：工作流操作界面
 */
var tabIframeId = request('tabIframeId');  // 当前窗口ID
var shcemeCode = request('shcemeCode');    // 流程模板编号
var type = request('type');                // 操作类型 0.创建 1.审批 2.重新创建 3.确认阅读 4.加签 100 流程进度查看

var processId = request('processId');      // 流程实例主键
var taskId = request('taskId');            // 任务主键

var currentNode;
var flowScheme;
var flowHistory = [];
var currentIds = [];

var allFormDatas = {};                     // 表单数据
var hideRightPanel = request("hideRightPanel");  //是否隐藏右侧面板

var bootstrap = function ($, learun) {
    "use strict";

    // 表单页面对象集合
    var formIframes = [];
    var formIframesData = {};
    var formIframesHave = {};


    var flow = {
        verify: function () { // 校验表单
            // 验证表单数据完整性和获取表单数据 //TODO 在此检查数据规则
            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (!formIframes[i].validForm()) {
                    return false;
                }
                var data = (!!formIframes[i].getFormData ? formIframes[i].getFormData() : {});
                var formId = formIframesData.length > i ? formIframesData[i].formId : "";
                var formData = data;
                if (!!processId) {
                    formData[processId] = processId;
                }
                var pass = formIframes[i].validBusinessData(formId, processId, formData);
                if (pass == false) {
                    return false;
                }
                $.extend(allFormDatas, data || {});
            }

            // 保存数据
            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (formIframesHave[i] != 1) {
                    formIframes[i].verifyBill(processId, function (res, data, _index) {
                        if (res.resp_code == learun.httpCode.success) {
                            $.extend(allFormDatas, data || {});
                        }
                    }, i);
                }
            }
        },
        draft: function (isNew) { // 发起流程方法
            // 验证表单数据完整性和获取表单数据 //TODO 在此检查数据规则
            for (var i = 0, l = formIframes.length; i < l; i++) {
                var data = (!!formIframes[i].getFormData ? formIframes[i].getFormData() : {});
                var formData = data;
                if (!!processId) {
                    formData[processId] = processId;
                }
                $.extend(allFormDatas, data || {});
            }

            var processName = $("#title").val();
            var level = $("input[name='processLevel']:checked").val();
            var force = $("input[name='processForce']:checked").val()
            var description = $("#description").val();
            // 获取审核人员
            var auditors = {};
            $('#form').find('.nodeId').each(function () {
                var $this = $(this);
                var id = $this.attr('id');
                var type = $this.attr('type');
                if (!!formData[id]) {
                    var point = {
                        userId: formData[id],
                    };
                    if (type == 'lrselect') {
                        point.userName = $this.find('.lr-select-placeholder').text();
                    } else {
                        point.userName = $this.find('span').text();
                    }
                    auditors[id] = point;
                }
            });

            // 保存数据
            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (formIframesHave[i] != 1) {
                    formIframes[i].saveDraft(processId, 1, function (res, data, _index) {
                        if (_index == undefined) {
                            _index = 0;
                        }
                        if (res.resp_code == learun.httpCode.success) {
                            formIframesHave[_index] = 1;

                            createProcess(); //从下面的位置弄到这里新建流程

                            $.extend(allFormDatas, data || {});
                        } else {
                            formIframesHave[_index] = 0;
                        }
                    }, i);
                }
            }

            // createProcess();

            function createProcess() {
                var num = 0;
                var flag = true;
                for (var i = 0, l = formIframes.length; i < l; i++) {
                    if (formIframesHave[i] == 0) {
                        num++;
                        flag = false;
                    } else if (formIframesHave[i] == 1) {
                        num++;
                    }
                }
                if (num == formIframes.length) {
                    if (flag) {
                        // 发起流程
                        learun.workflowapi.create({
                            isNew: isNew,
                            schemeCode: shcemeCode,
                            processId: processId,
                            processName: processName,
                            processLevel: level,
                            description: description,
                            auditors: JSON.stringify(auditors),
                            formData: JSON.stringify(allFormDatas),
                            callback: function (res, data) {
                                if (res) {
                                    learun.httpAsync('Post', config.base_server() + 'wftasks/revoke/' + processId + '?access_token=' + config.getToken().access_token, {}, function (data) {
                                        top.learun.frameTab.close(top.learun.frameTab.iframeId);
                                    });
                                }
                            }
                        });
                    } else {
                        learun.alert.error('表单数据保存失败');
                    }
                } else {
                    setTimeout(function () {
                        createProcess();  //TODO 待注销
                    }, 800);
                }
            }

        },
        release: function (isNew) { // 发起流程方法
            // 验证表单数据完整性和获取表单数据 //TODO 在此检查数据规则
            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (!formIframes[i].validForm()) {
                    return false;
                }
                var data = (!!formIframes[i].getFormData ? formIframes[i].getFormData() : {});
                var formId = formIframesData.length > i ? formIframesData[i].formId : "";
                var formData = data;
                if (!!processId) {
                    formData[processId] = processId;
                }
                var pass = formIframes[i].validBusinessData(formId, processId, formData);
                if (pass == false) {
                    return false;
                }
                $.extend(allFormDatas, data || {});
            }

            var processName = $("#title").val();
            var level = $("input[name='processLevel']:checked").val();
            var force = $("input[name='processForce']:checked").val()
            var description = $("#description").val();
            // 获取审核人员
            var auditors = {};
            $('#form').find('.nodeId').each(function () {
                var $this = $(this);
                var id = $this.attr('id');
                var type = $this.attr('type');
                if (!!formData[id]) {
                    var point = {
                        userId: formData[id],
                    };
                    if (type == 'lrselect') {
                        point.userName = $this.find('.lr-select-placeholder').text();
                    } else {
                        point.userName = $this.find('span').text();
                    }
                    auditors[id] = point;
                }
            });

            // 保存数据
            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (formIframesHave[i] != 1) {
                    formIframes[i].save(processId, force, function (res, data, _index) {
                        if (_index == undefined) {
                            _index = 0;
                        }
                        if (res.resp_code == learun.httpCode.success) {
                            formIframesHave[_index] = 1;

                            createProcess(); //从下面的位置弄到这里新建流程

                            $.extend(allFormDatas, data || {});
                        } else {
                            formIframesHave[_index] = 0;
                        }
                    }, i);
                }
            }

            // createProcess();

            function createProcess() {
                var num = 0;
                var flag = true;
                for (var i = 0, l = formIframes.length; i < l; i++) {
                    if (formIframesHave[i] == 0) {
                        num++;
                        flag = false;
                    } else if (formIframesHave[i] == 1) {
                        num++;
                    }
                }
                if (num == formIframes.length) {
                    if (flag) {
                        // 发起流程
                        learun.workflowapi.create({
                            isNew: isNew,
                            schemeCode: shcemeCode,
                            processId: processId,
                            processName: processName,
                            processLevel: level,
                            description: description,
                            auditors: JSON.stringify(auditors),
                            formData: JSON.stringify(allFormDatas),
                            callback: function (res, data) {
                                if (res) {
                                    //learun.frameTab.parentIframe().refreshGirdData();
                                    top.learun.frameTab.close(top.learun.frameTab.iframeId);
                                }
                            }
                        });
                    } else {
                        learun.alert.error('表单数据保存失败');
                    }
                } else {
                    setTimeout(function () {
                        createProcess();  //TODO 待注销
                    }, 800);
                }
            }
        },
        audit: function (verifyType) { // 审核流程
            var force = $("input[name='processForce']:checked").val();
            if (verifyType == 2) { //不同意不保存校验
                force = 1;
            }

            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (!formIframes[i].validForm(verifyType)) {
                    return false;
                }
                var data = (!!formIframes[i].getFormData ? formIframes[i].getFormData() : {});
                $.extend(allFormDatas, data || {});
            }

            var description = $("#description").val();
            // 获取审核人员
            var auditors = {};
            $('#form').find('.nodeId').each(function () {
                var $this = $(this);
                var id = $this.attr('id');
                var type = $this.attr('type');
                if (!!formData[id]) {
                    var point = {
                        userId: formData[id],
                    };
                    if (type == 'lrselect') {
                        point.userName = $this.find('.lr-select-placeholder').text();
                    } else {
                        point.userName = $this.find('span').text();
                    }
                    auditors[id] = point;
                }
            });

            // 保存数据
            for (var i = 0, l = formIframes.length; i < l; i++) {
                if (formIframesHave[i] != 1) {
                    formIframes[i].save(processId, force, function (res, data, _index) {
                        if (_index == undefined) {
                            _index = 0;
                        }
                        if (res.resp_code == learun.httpCode.success) {
                            formIframesHave[_index] = 1;
                            $.extend(allFormDatas, data || {});
                        } else {
                            formIframesHave[_index] = 0;
                        }
                    }, i);
                }
            }
            auditProcess();

            function auditProcess() {
                var num = 0;
                var flag = true;
                for (var i = 0, l = formIframes.length; i < l; i++) {
                    if (formIframesHave[i] == 0) {
                        num++;
                        flag = false;
                    } else if (formIframesHave[i] == 1) {
                        num++;
                    }
                }
                if (num == formIframes.length) {
                    if (flag) {
                        // 审核流程
                        if (type == 4) {// 加签的情况
                            verifyType = parseInt(verifyType) + 3;
                        }
                        learun.workflowapi.audit({
                            taskId: taskId,
                            verifyType: verifyType,
                            description: description,
                            formData: JSON.stringify(allFormDatas),
                            auditors: JSON.stringify(auditors),
                            callback: function (res, data) {
                                if (res) {
                                    //learun.frameTab.parentIframe().refreshGirdData();
                                    top.learun.frameTab.close(top.learun.frameTab.iframeId);
                                }
                            }
                        });
                    } else {
                        learun.alert.error('表单数据保存失败');
                    }
                } else {
                    setTimeout(function () {
                        auditProcess();
                    }, 100);
                }
            }
        },
        sign: function () { // 加签流程
            var force = $("input[name='processForce']:checked").val()

            learun.layerForm({
                id: 'AuditFlowForm',
                title: '加签审核',
                url: config.webportal_server + 'pages/workflow/wfmyTask/signFlowForm.html?access_token=' + config.getToken().access_token,
                width: 600,
                height: 400,
                callBack: function (id) {
                    return top[id].acceptClick(function (formData) {
                        // 验证表单数据完整性
                        for (var i = 0, l = formIframes.length; i < l; i++) {
                            if (!formIframes[i].validForm()) {
                                return false;
                            }
                        }
                        // 保存数据
                        for (var i = 0, l = formIframes.length; i < l; i++) {
                            if (formIframesHave[i] != 1) {
                                formIframes[i].save(processId, force, function (res, data, _index) {
                                    if (res.resp_code == learun.httpCode.success) {
                                        formIframesHave[_index] = 1;
                                        $.extend(formData, data || {});
                                    } else {
                                        formIframesHave[_index] = 0;
                                    }
                                }, i);
                            }
                        }
                        signProcess();

                        function signProcess() {
                            var num = 0;
                            var flag = true;
                            for (var i = 0, l = formIframes.length; i < l; i++) {
                                if (formIframesHave[i] == 0) {
                                    num++;
                                    flag = false;
                                } else if (formIframesHave[i] == 1) {
                                    num++;
                                }
                            }
                            if (num == formIframes.length) {
                                if (flag) {
                                    // 审核流程
                                    learun.workflowapi.audit({
                                        taskId: taskId,
                                        verifyType: 3,
                                        auditorId: formData.auditorId,
                                        auditorName: formData.auditorName,
                                        description: formData.description,
                                        formData: JSON.stringify(allFormDatas),
                                        callback: function (res, data) {
                                            if (res) {
                                                //learun.frameTab.parentIframe().refreshGirdData();
                                                top.learun.frameTab.close(top.learun.frameTab.iframeId);
                                            }
                                        }
                                    });
                                } else {
                                    learun.alert.error('表单数据保存失败');
                                }
                            } else {
                                setTimeout(function () {
                                    signProcess();
                                }, 100);
                            }
                        }
                    });
                }
            });
        },
        feeProjectAssign: function () { // 项目预算分配
            var costData = [];
            var costDataTmp = $('#gridtable_projectinfo').jfGridGet('rowdatas');

            for (var i = 0, l = costDataTmp.length; i < l; i++) {
                if (!!costDataTmp[i]['projectId']) {
                    costDataTmp[i].processId = processId;
                    costData.push(costDataTmp[i]);
                }
            }

            learun.httpPost(config.base_server() + 'billfeeprojectassigns/saveOrUpdate?access_token=' + config.getToken().access_token, JSON.stringify(costData), null);
        },
    };

    var page = {
        init: function () {
            page.bind();
            page.initflow();
        },
        bind: function () {
            // 显示信息选项卡
            $('#tablist').lrFormTabEx(function (id) {
                if (id == 'workflowshcemeinfo' || id == 'auditinfo') {
                    $('#print').hide();
                } else {
                    $('#print').show();
                }
            });

            //嵌入页面隐藏右侧面板
            if (hideRightPanel == 1) {
                $("#lr-layout-panel").css("padding-right", "50px");
                $(".lr-layout-panel-right").hide();
            }

            $('#print').show();
            // 表单选项卡点击事件
            $('#form_list_tabs').delegate('a', 'click', function () {
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    $this.parents('ul').find('.active').removeClass('active');
                    $this.parent().addClass('active');

                    var value = $this.attr('data-value');
                    var $iframes = $('#form_list_iframes');
                    $iframes.find('.active').removeClass('active');
                    $iframes.find('[data-value="' + value + '"]').addClass('active');
                }
            });

            $('#flow').lrworkflow({
                isPreview: true,
                openNode: function (node) {
                    currentNode = node;

                    if (!!node.history) {
                        learun.layerForm({
                            id: 'WfNodeForm',
                            title: '审核记录查看【' + node.name + '】',
                            url: config.webportal_server + 'pages/workflow/wfmyTask/wfNodeForm.html?access_token=' + config.getToken().access_token,
                            width: 600,
                            height: 400,
                            btn: null
                        });
                    }
                }
            });

            // 打印表单  TODO 绑定机构和表单模板
            $('#print').on('click', function () {
                var hiprintTemplate = null;
                learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', '&code=' + formIframesData[0].code, function (res) {
                    if (res.resp_code == 200) {
                        hiprintTemplate = new hiprint.PrintTemplate({
                            template: JSON.parse(res.data.templete),
                            settingContainer: '#PrintElementOptionSetting',
                            paginationContainer: '.hiprint-printPagination'
                        });
                        var action = formIframesData[0].code.replace("bill_", "").replace("_", "") + "s";
                        $.lrSetForm2(config.base_server() + action + '/findById', '&id=' + processId + '&processId=' + processId, function (data) {
                            if (!!data) {
                                var createDate = new Date(data.createTime);
                                var year0 = createDate.getFullYear();
                                var month0 = createDate.getMonth() + 1;
                                var date0 = createDate.getDate();

                                var startTime = new Date(data.startTime + ":00:00");
                                var year1 = startTime.getFullYear();
                                var month1 = startTime.getMonth() + 1;
                                var date1 = startTime.getDate();
                                var hour1 = startTime.getHours() < 10 ? "0" + startTime.getHours() : startTime.getHours();

                                var endTime = new Date(data.endTime + ":00:00");
                                var year2 = endTime.getFullYear();
                                var month2 = endTime.getMonth() + 1;
                                var date2 = endTime.getDate();
                                var hour2 = endTime.getHours() < 10 ? "0" + endTime.getHours() : endTime.getHours();

                                var item = {};
                                item.create_date_str = year0 + "年" + month0 + "月" + date0 + "日";
                                data.kjnd = year0;
                                data.month = month0;
                                data.day = date0;
                                data.startTimeStr = year1 + "年" + month1 + "月" + date1 + "日";// + hour1 + "时";
                                data.endTimeStr = year2 + "年" + month2 + "月" + date2 + "日";// + hour2 + "时";

                                if (!!data.site) {
                                    data.destinationStr = data.destinationStr + data.site;
                                }

                                data.cost = $.formatMoney(data.cost, 2);

                                var count = 0;
                                count = count + data.number9;
                                data.number9 = $.chineseNumber(count > 0 ? data.number9 : 0);
                                count = count + data.number8;
                                data.number8 = $.chineseNumber(count > 0 ? data.number8 : 0);
                                count = count + data.number7;
                                data.number7 = $.chineseNumber(count > 0 ? data.number7 : 0);
                                count = count + data.number6;
                                data.number6 = $.chineseNumber(count > 0 ? data.number6 : 0);
                                count = count + data.number5;
                                data.number5 = $.chineseNumber(count > 0 ? data.number5 : 0);
                                count = count + data.number4;
                                data.number4 = $.chineseNumber(count > 0 ? data.number4 : 0);
                                count = count + data.number3;
                                data.number3 = $.chineseNumber(count > 0 ? data.number3 : 0);
                                count = count + data.number2;
                                data.number2 = $.chineseNumber(count > 0 ? data.number2 : 0);
                                count = count + data.number1;
                                data.number1 = $.chineseNumber(count > 0 ? data.number1 : 0);

                                var strMoney = data.cost.replace(".", "").replace(",", "");
                                switch (strMoney.length) {
                                    case 1:
                                        data.number2 = "￥";
                                        data.number3 = "";
                                        data.number4 = "";
                                        data.number5 = "";
                                        data.number6 = "";
                                        data.number7 = "";
                                        data.number8 = "";
                                        data.number9 = "";
                                        break;
                                    case 2:
                                        data.number3 = "￥";
                                        data.number4 = "";
                                        data.number5 = "";
                                        data.number6 = "";
                                        data.number7 = "";
                                        data.number8 = "";
                                        data.number9 = "";
                                        break;
                                    case 3:
                                        data.number4 = "￥";
                                        data.number5 = "";
                                        data.number6 = "";
                                        data.number7 = "";
                                        data.number8 = "";
                                        data.number9 = "";
                                        break;
                                    case 4:
                                        data.number5 = "￥";
                                        data.number6 = "";
                                        data.number7 = "";
                                        data.number8 = "";
                                        data.number9 = "";
                                        break;
                                    case 5:
                                        data.number6 = "￥";
                                        data.number7 = "";
                                        data.number8 = "";
                                        data.number9 = "";
                                        break;
                                    case 7:
                                        data.number8 = "￥";
                                        data.number9 = "";
                                        break;
                                    case 8:
                                        data.number9 = "￥";
                                        break;
                                }

                                if (!!data.vehicle) {
                                    if (data.vehicle.indexOf(1) >= 0) {
                                        data.isPlane = "√";
                                    }
                                    if (data.vehicle.indexOf(2) >= 0) {
                                        data.isTrain = "√";
                                    }
                                    if (data.vehicle.indexOf(3) >= 0) {
                                        data.isBus = "√";
                                    }
                                    if (data.vehicle.indexOf(4) >= 0) {
                                        data.isShip = "√";
                                    }
                                    if (data.vehicle.indexOf(5) >= 0) {
                                        data.isOther = "√";
                                    }
                                }

                                if (!!data.costList) {
                                    for (var i = 0; i < data.costList.length; i++) {
                                        var itemName = "";
                                        switch (data.costList[i].itemCode) {
                                            case "1":
                                                itemName = "住宿费";
                                                break;
                                            case "2":
                                                itemName = "机票费";
                                                break;
                                            case "3":
                                                itemName = "火车票";
                                                break;
                                            case "4":
                                                itemName = "伙食补助";
                                                break;
                                            case "5":
                                                itemName = "市内交通补助";
                                                break;
                                            case "6":
                                                itemName = "场地费";
                                                break;
                                            case "7":
                                                itemName = "师资费(正高)";
                                                break;
                                            case "8":
                                                itemName = "师资费(副高)";
                                                break;
                                            case "9":
                                                itemName = "师资费(普通)";
                                                break;
                                            case "99":
                                                itemName = "其他费";
                                                break;

                                            default:
                                                itemName = data.costList[i].itemCode;
                                        }

                                        if (i == 0) {
                                            data.itemCode1 = itemName;
                                            data.price1 = $.formatMoney(data.costList[i].price,2);
                                            data.day1 = data.costList[i].days;
                                            data.person1 = data.costList[i].persons;
                                            data.money1 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime1 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark1 = data.costList[i].remark;
                                        }
                                        if (i == 1) {
                                            data.itemCode2 = itemName;
                                            data.price2 = $.formatMoney(data.costList[i].price,2);
                                            data.day2 = data.costList[i].days;
                                            data.person2 = data.costList[i].persons;
                                            data.money2 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime2 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark2 = data.costList[i].remark;
                                        }
                                        if (i == 2) {
                                            data.itemCode3 = itemName;
                                            data.price3 = $.formatMoney(data.costList[i].price,2);
                                            data.day3 = data.costList[i].days;
                                            data.person3 = data.costList[i].persons;
                                            data.money3 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime3 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark3 = data.costList[i].remark;
                                        }
                                        if (i == 3) {
                                            data.itemCode4 = itemName;
                                            data.price4 = $.formatMoney(data.costList[i].price,2);
                                            data.day4 = data.costList[i].days;
                                            data.person4 = data.costList[i].persons;
                                            data.money4 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime4 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark4 = data.costList[i].remark;
                                        }
                                        if (i == 4) {
                                            data.itemCode5 = itemName;
                                            data.price5 = $.formatMoney(data.costList[i].price,2);
                                            data.day5 = data.costList[i].days;
                                            data.person5 = data.costList[i].persons;
                                            data.money5 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime5 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark5 = data.costList[i].remark;
                                        }
                                        if (i == 5) {
                                            data.itemCode6 = itemName;
                                            data.price6 = $.formatMoney(data.costList[i].price,2);
                                            data.day6 = data.costList[i].days;
                                            data.person6 = data.costList[i].persons;
                                            data.money6 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime6 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark6 = data.costList[i].remark;
                                        }
                                        if (i == 6) {
                                            data.itemCode7 = itemName;
                                            data.price7 = $.formatMoney(data.costList[i].price,2);
                                            data.day7 = data.costList[i].days;
                                            data.person7 = data.costList[i].persons;
                                            data.money7 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime7 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark7 = data.costList[i].remark;
                                        }
                                        if (i == 7) {
                                            data.itemCode8 = itemName;
                                            data.price8 = $.formatMoney(data.costList[i].price,2);
                                            data.day8 = data.costList[i].days;
                                            data.person8 = data.costList[i].persons;
                                            data.money8 = $.formatMoney(data.costList[i].money,2);
                                            data.startTime8 = data.costList[i].startTime + "至" + data.costList[i].endTime;
                                            data.remark8 = data.costList[i].remark;
                                        }
                                    }
                                }

                                if(!!data.followUsernames) {
                                    data.usernameAll = data.username + '、' + data.followUsernames
                                }
                                hiprintTemplate.print(data);
                            } else {
                                hiprintTemplate.print(null);
                            }
                        });
                    }
                });
            });
        },

        // 初始化流程信息
        initflow: function () {
            switch (type) {
                case '0': // 创建流程（第一次创建）
                    // 生成流程实例ID
                    processId = learun.newGuid();
                case '2': // 重新创建流程
                    learun.workflowapi.bootstraper({
                        isNew: type == 0 ? true : false,
                        processId: processId,
                        schemeCode: shcemeCode,
                        callback: function (res, data) {
                            if (res) {
                                // 初始化页面组件
                                $('#release').on('click', function () {
                                    if (type == '0') {
                                        flow.release(true);
                                    } else {
                                        flow.release(false);
                                    }

                                });
                                $('#release').show();
                                $('#savedraft').on('click', function () {
                                    if (type == '0') {
                                        flow.draft(true);
                                    } else {
                                        flow.draft(false);
                                    }

                                });
                                $('#savedraft').show();
                                $('#verifyBill').on('click', function () {
                                    flow.verify();
                                });
                                $('#verifyBill').show();

                                // 初始化表单信息
                                var startnode = data.currentNode;
                                currentNode = startnode;

                                var $ul = $('#form_list_tabs');
                                var $iframes = $('#form_list_iframes');
                                for (var i = 0, l = startnode.forms.length; i < l; i++) {
                                    var forminfo = startnode.forms[i];
                                    forminfo = forminfo;
                                    $ul.append('<li><a data-value="' + i + '" >' + forminfo.name + '</a></li>');
                                    $iframes.append('<iframe id="wfFormIframe' + i + '" class="form-list-iframe" data-value="' + i + '" frameborder="0" ></iframe>');
                                    if (i == 0) {
                                        $ul.find('a').trigger('click');
                                    }
                                    formIframesData[i] = forminfo;
                                    page.iframeLoad("wfFormIframe" + i, forminfo.url, function (iframeObj, _index) {
                                        // 设置字段权限
                                        iframeObj.setAuthorize(startnode.authorizeFields);
                                        if (!!formIframesData[_index].field) {
                                            iframeObj.processId = formIframesData[_index].field;
                                        }
                                        iframeObj.setFormData(processId);
                                    }, i);
                                }
                                // 优化表单选项卡滚动条
                                $('#form_list_tabs_warp').lrscroll();
                                // 初始化流程信息和审核记录信息
                                flowScheme = JSON.parse(data.scheme);
                                flowHistory = data.historys || [];
                                currentIds = data.currentNodeIds || [];
                                initScheme();
                                initTimeLine(flowHistory);
                            } else {
                                top.learun.frameTab.close(top.learun.frameTab.iframeId);
                            }
                        }
                    });
                    //获取下一个节点的审核人信息数据
                    //initNextAuditer();  //ftquan  取消下一个负责人手工选择 at20210819
                    break;
                case '4':// 加签
                case '1':// 审核
                    learun.workflowapi.taskinfo({
                        processId: processId,
                        taskId: taskId,
                        callback: function (res, data) {
                            if (res) {
                                // 初始化页面组件
                                //隐藏发起按钮
                                $('#flow-title').hide();
                                $('#flow-level').hide();
                                $('#flow-force').hide();
                                $('#release').hide();
                                $('#sign').hide();
                                $('#confirm').hide();
                                $('#savedraft').hide();
                                $('#verifyBill').hide();

                                // 加载审批按钮
                                var $signBtn = $('#flow-btn');
                                $.each([{id: "1", name: "同意", code: "agree", file: "1", next: "1"},
                                        {id: "2", name: "不同意", code: "disagree", file: "1", next: "1"}],
                                    function (_index, _item) {
                                        if (_item.isHide != '1') {
                                            var _class = ' btn-warning';
                                            if (_item.code == 'agree') {
                                                _class = ' btn-success';
                                            } else if (_item.code == 'disagree') {
                                                _class = ' btn-danger';
                                            }

                                            var $btn = $('<a class="verifybtn btn ' + _class + '" data-value="' + _item.code + '"  >' + _item.name + '</a>');
                                            $btn[0].lrbtn = _item;
                                            $signBtn.append($btn);
                                        }
                                    });
                                // 审核
                                $('.verifybtn').on('click', function () {
                                    var verifyType = $(this).attr("data-value");
                                    if (verifyType == 'agree') {
                                        flow.audit(1);
                                    } else {
                                        flow.audit(2);
                                    }
                                });
                                // 加签
                                $('#sign').on('click', function () {
                                    flow.sign();
                                });
                                $('#sign').show();
                                $('#flow-des div').html("审批意见");

                                $('#savedraft').show();
                                $('#verifyBill').show();

                                // 初始化表单信息
                                currentNode = data.currentNode;

                                var $ul = $('#form_list_tabs');
                                var $iframes = $('#form_list_iframes');
                                for (var i = 0, l = currentNode.forms.length; i < l; i++) {
                                    var forminfo = currentNode.forms[i];
                                    $ul.append('<li><a data-value="' + i + '" >' + forminfo.name + '</a></li>');
                                    $iframes.append('<iframe id="wfFormIframe' + i + '" class="form-list-iframe" data-value="' + i + '" frameborder="0" ></iframe>');
                                    if (i == 0) {
                                        $ul.find('a').trigger('click');
                                    }
                                    formIframesData[i] = forminfo;
                                    page.iframeLoad("wfFormIframe" + i, forminfo.url, function (iframeObj, _index) {
                                        // 设置字段权限
                                        iframeObj.setAuthorize(currentNode.authorizeFields);
                                        if (!!formIframesData[_index].field) {
                                            iframeObj.processId = formIframesData[_index].field;
                                        }
                                        iframeObj.setFormData(processId);
                                    }, i);
                                }

                                // 优化表单选项卡滚动条
                                $('#form_list_tabs_warp').lrscroll();

                                // 初始化流程信息
                                flowScheme = JSON.parse(data.scheme);
                                flowHistory = data.historys || [];
                                currentIds = data.currentNodeIds || [];
                                initScheme();
                                initTimeLine(flowHistory);
                            } else {
                                top.learun.frameTab.close(top.learun.frameTab.iframeId);
                            }
                        }
                    });
                    break;
                case '3':// 查阅
                    learun.workflowapi.taskinfo({
                        processId: processId,
                        taskId: taskId,
                        callback: function (res, data) {
                            if (res) {
                                $('#confirm').show();
                                $('#confirm').on('click', function () {
                                    learun.layerConfirm('是否确认阅读！', function (res, index) {
                                        if (res) {
                                            learun.workflowapi.audit({
                                                taskId: taskId,
                                                verifyType: '6',
                                                description: '',
                                                formData: JSON.stringify({}),
                                                auditors: JSON.stringify({}),
                                                callback: function (res, data) {
                                                    if (res) {
                                                        //learun.frameTab.parentIframe().refreshGirdData();
                                                        top.learun.frameTab.close(top.learun.frameTab.iframeId);
                                                    }

                                                    learun.layerClose('', index); //再执行关闭
                                                }
                                            });

                                        }
                                    });
                                });

                                // 初始化表单信息
                                currentNode = data.currentNode;
                                //隐藏发起按钮
                                $('#flow-level').hide();
                                $('#flow-force').hide();
                                $('#sign').hide();
                                $('#release').hide();
                                $('#savedraft').hide();
                                $('#verifyBill').hide();

                                var $ul = $('#form_list_tabs');
                                var $iframes = $('#form_list_iframes');
                                for (var i = 0, l = currentNode.forms.length; i < l; i++) {
                                    var forminfo = currentNode.forms[i];
                                    $ul.append('<li><a data-value="' + i + '" >' + forminfo.name + '</a></li>');
                                    $iframes.append('<iframe id="wfFormIframe' + i + '" class="form-list-iframe" data-value="' + i + '" frameborder="0" ></iframe>');
                                    if (i == 0) {
                                        $ul.find('a').trigger('click');
                                    }
                                    formIframesData[i] = forminfo;
                                    page.iframeLoad("wfFormIframe" + i, forminfo.url, function (iframeObj, _index) {
                                        // 设置字段权限
                                        iframeObj.setAuthorize(currentNode.authorizeFields);
                                        if (!!formIframesData[_index].field) {
                                            iframeObj.processId = formIframesData[_index].field;
                                        }
                                        iframeObj.setFormData(processId, 3);
                                    }, i);
                                }

                                // 优化表单选项卡滚动条
                                $('#form_list_tabs_warp').lrscroll();

                                // 初始化流程信息
                                flowScheme = JSON.parse(data.scheme);
                                flowHistory = data.historys || [];
                                currentIds = data.currentNodeIds || [];
                                initScheme();
                                initTimeLine(flowHistory);

                            } else {
                                top.learun.frameTab.close(top.learun.frameTab.iframeId);
                            }
                        }
                    });
                    break;
                case '100':// 审批
                    learun.workflowapi.processinfo({
                        processId: processId,
                        taskId: taskId,
                        callback: function (res, data) {
                            if (res) {
                                // 初始化表单信息
                                currentNode = data.currentNode;

                                //判断当前用户的权限
                                $.ajax({
                                    url: config.base_server() + 'wftasks/' + processId + '/checkPermission?access_token=' + config.getToken().access_token,
                                    data: {taskId: taskId, nodeId: currentNode.id},
                                    type: 'GET',
                                    success: function (res) {
                                        var checkPermission = res.data;
                                        //隐藏发起按钮
                                        $('#flow-title').hide();
                                        $('#flow-level').hide();
                                        $('#flow-force').hide();
                                        $('#release').hide();
                                        $('#sign').hide();
                                        $('#confirm').hide();
                                        $('#savedraft').hide();
                                        $('#verifyBill').hide();
                                        $('#flow-des').hide();

                                        if (checkPermission) {//TODO 手写签名

                                            $('#flow-handSignature').show();
                                            // 加载手写签名按钮
                                            // 签名
                                            $('.signaturebtn').on('click', function () {
                                               learun.layerForm({
                                                   id: 'signaturebtn',
                                                   title: '手写签名',
                                                   url: config.webportal_server + 'pages/workflow/handSignature2/index.html?access_token=' + config.getToken().access_token,
                                                   width: 1024,
                                                   height: 768,
                                                   btn: null
                                               });
                                            });
                                        }

                                        if (checkPermission) {
                                            // 加载审批按钮
                                            var $signBtn = $('#flow-btn');
                                            $.each([{id: "1", name: "同意", code: "agree", file: "1", next: "1"},
                                                    {id: "2", name: "不同意", code: "disagree", file: "1", next: "1"}],
                                                function (_index, _item) {
                                                    if (_item.isHide != '1') {
                                                        var _class = ' btn-warning';
                                                        if (_item.code == 'agree') {
                                                            _class = ' btn-success';
                                                        } else if (_item.code == 'disagree') {
                                                            _class = ' btn-danger';
                                                        }

                                                        var $btn = $('<a class="verifybtn btn ' + _class + '" data-value="' + _item.code + '"  >' + _item.name + '</a>');
                                                        $btn[0].lrbtn = _item;
                                                        $signBtn.append($btn);
                                                    }
                                                });
                                            // 审核
                                            $('.verifybtn').on('click', function () {
                                                var verifyType = $(this).attr("data-value");
                                                if (verifyType == 'agree') {
                                                    flow.audit(1);

                                                    //项目预算分配
                                                    flow.feeProjectAssign();

                                                } else {
                                                    flow.audit(2);
                                                }
                                            });
                                            $('#flow-des').show();

                                            //显示项目预算信息
                                            $('#gridtable_projectinfo').jfGrid({
                                                url: config.base_server() + 'billfeeprojectassigns/findByProcessId?id=' + processId + '&access_token=' + config.getToken().access_token,
                                                headData: [
                                                    {
                                                        label: '项目id',
                                                        name: 'projectId',
                                                        width: 1,
                                                        align: 'left',
                                                        hidden: true
                                                    },
                                                    {
                                                        label: '项目', name: 'projectName', width: 120, align: 'left',
                                                        edit: {
                                                            type: 'select',
                                                            op: {
                                                                value: 'name',
                                                                text: 'name',
                                                                title: 'name',
                                                                url: config.base_server() + 'pbdprojectas/list?access_token=' + config.getToken().access_token,
                                                                param: {},
                                                            },
                                                            change: function (row, num, selectdata) {// 行数据和行号
                                                                if (!!selectdata) {
                                                                    row.projectId = selectdata.id;
                                                                }
                                                                $('#gridtable_projectinfo').jfGridSet('updateRow', num);
                                                            }
                                                        }
                                                    },
                                                    {
                                                        label: '项目id',
                                                        name: 'economicId',
                                                        width: 1,
                                                        align: 'left',
                                                        hidden: true
                                                    },
                                                    {
                                                        label: '经济科目', name: 'economicName', width: 120, align: 'left',
                                                        edit: {
                                                            type: 'select',
                                                            op: {
                                                                value: 'name',
                                                                text: 'name',
                                                                title: 'name',
                                                                url: config.base_server() + 'dictDatas/list?access_token=' + config.getToken().access_token,
                                                                param: {code: 'Economics'},
                                                            },
                                                            change: function (row, num, selectdata) {// 行数据和行号
                                                                var data = (!!formIframes[0].getFormData ? formIframes[0].getFormData() : {});
                                                                var money = 0.00;
                                                                for (var i = 0; i < data.costList.length; i++) {
                                                                    money += data.costList[i].money;
                                                                }
                                                                if (!!selectdata) {
                                                                    row.economicId = selectdata.value;
                                                                    row.money = money;
                                                                }
                                                                $('#gridtable_projectinfo').jfGridSet('updateRow', num);
                                                            }
                                                        }
                                                    },
                                                    {
                                                        label: '金额', name: 'money', width: 100, align: 'right',
                                                        formatter: function (cellvalue) {
                                                            return $.formatMoney(cellvalue, 2)
                                                        },
                                                        edit: {
                                                            type: 'number'
                                                        }
                                                    }
                                                ],
                                                isEdit: true,
                                                isPage: false,
                                                isShowNum: false,
                                                reloadSelected: true,
                                                mainId: 'id'
                                            });
                                            $('#gridtable_projectinfo').jfGridSet('reload', {});
                                            $('#gridtable_projectinfo').jfGridSet('addRow', {});
                                        }

                                        var $ul = $('#form_list_tabs');
                                        var $iframes = $('#form_list_iframes');
                                        for (var i = 0, l = currentNode.forms.length; i < l; i++) {
                                            var forminfo = currentNode.forms[i];
                                            $ul.append('<li><a data-value="' + i + '" >' + forminfo.name + '</a></li>');
                                            $iframes.append('<iframe id="wfFormIframe' + i + '" class="form-list-iframe" data-value="' + i + '" frameborder="0" ></iframe>');
                                            if (i == 0) {
                                                $ul.find('a').trigger('click');
                                            }
                                            formIframesData[i] = forminfo;
                                            page.iframeLoad("wfFormIframe" + i, forminfo.url, function (iframeObj, _index) {
                                                // 设置字段权限
                                                iframeObj.setAuthorize(currentNode.authorizeFields);
                                                if (!!formIframesData[_index].field) {
                                                    iframeObj.processId = formIframesData[_index].field;
                                                }
                                                iframeObj.setFormData(processId, 100, checkPermission, forminfo.upload);
                                            }, i);
                                        }

                                        // 优化表单选项卡滚动条
                                        $('#form_list_tabs_warp').lrscroll();

                                        // 初始化流程信息
                                        flowScheme = JSON.parse(data.scheme);
                                        flowHistory = data.historys || [];
                                        currentIds = data.currentNodeIds || [];
                                        initScheme();
                                        initTimeLine(flowHistory);

                                    }
                                });
                            } else {
                                top.learun.frameTab.close(top.learun.frameTab.iframeId);
                            }
                        }
                    });
                    break;
                case '101':// 加签审批
                    learun.workflowapi.processinfoByMonitor({
                        processId: processId,
                        taskId: taskId,
                        callback: function (res, data) {
                            if (res) {
                                // 初始化表单信息
                                currentNode = data.currentNode;

                                var $ul = $('#form_list_tabs');
                                var $iframes = $('#form_list_iframes');
                                for (var i = 0, l = currentNode.forms.length; i < l; i++) {
                                    var forminfo = currentNode.forms[i];
                                    $ul.append('<li><a data-value="' + i + '" >' + forminfo.name + '</a></li>');
                                    $iframes.append('<iframe id="wfFormIframe' + i + '" class="form-list-iframe" data-value="' + i + '" frameborder="0" ></iframe>');
                                    if (i == 0) {
                                        $ul.find('a').trigger('click');
                                    }
                                    formIframesData[i] = forminfo;
                                    page.iframeLoad("wfFormIframe" + i, forminfo.url, function (iframeObj, _index) {
                                        // 设置字段权限
                                        iframeObj.setAuthorize(currentNode.authorizeFields);
                                        if (!!formIframesData[_index].field) {
                                            iframeObj.processId = formIframesData[_index].field;
                                        }
                                        iframeObj.setFormData(processId);
                                    }, i);
                                }

                                // 优化表单选项卡滚动条
                                $('#form_list_tabs_warp').lrscroll();

                                // 初始化流程信息
                                flowScheme = JSON.parse(data.scheme);
                                flowHistory = data.historys || [];
                                currentIds = data.currentNodeIds || [];
                                initScheme();
                                initTimeLine(flowHistory);
                            } else {
                                top.learun.frameTab.close(top.learun.frameTab.iframeId);
                            }
                        }
                    });
                    break;
            }
        },
        // iframe 加载
        iframeLoad: function (iframeId, url, callback, i) {
            var _iframe = document.getElementById(iframeId);
            var _iframeLoaded = function () {
                var iframeObj = learun.iframe(iframeId, frames);
                formIframes.push(iframeObj);
                if (!!iframeObj.$) {
                    callback(iframeObj, i);
                }
            };

            if (_iframe.attachEvent) {
                _iframe.attachEvent("onload", _iframeLoaded);
            } else {
                _iframe.onload = _iframeLoaded;
            }
            setTimeout(function () {
                $('#' + iframeId).attr('src', url);
            }, i * 500);

        }
    };

    function initNextAuditer() {
        // 获取下一个节点的审核人信息数据
        learun.workflowapi.auditer({
            isNew: (!!shcemeCode) ? true : false,
            schemeCode: shcemeCode,
            processId: processId,
            taskId: taskId,
            formData: JSON.stringify(allFormDatas),
            callback: function (res) {
                console.log(res);
                var $form = $('#description').parent();
                $.each(res.data, function (_i, _item) {
                    if (_item.all || _item.auditors.length == 0) {
                        //$form.before('<div class="col-xs-12 lr-form-item"><div class="lr-form-item-title" >' + _item.nodeName + '</div><div id="' + _item.nodeId + '" class="nodeId"></div></div >');
                        var auditerHtml = '';
                        auditerHtml += ' <div class="col-xs-12 lr-form-item flow-item" style="padding:0;" >';
                        auditerHtml += '     <div class="lr-form-item-title" style="position:relative;width:100%;text-align:left;">' + _item.nodeName + '</div>';
                        auditerHtml += '     <div id="' + _item.nodeId + '" class="nodeId"></div>';
                        auditerHtml += ' </div>';
                        $form.before(auditerHtml);
                        $('#' + _item.nodeId).lrUserSelect(0);
                    } else if (_item.auditors.length > 1) {
                        //$form.before('<div class="col-xs-12 lr-form-item"><div class="lr-form-item-title" >' + _item.nodeName + '</div><div id="' + _item.nodeId + '" class="nodeId" ></div></div >');
                        var auditerHtml = '';
                        auditerHtml += ' <div class="col-xs-12 lr-form-item flow-item" style="padding:0;" >';
                        auditerHtml += '     <div class="lr-form-item-title" style="position:relative;width:100%;text-align:left;">' + _item.nodeName + '</div>';
                        auditerHtml += '     <div id="' + _item.nodeId + '" class="nodeId"></div>';
                        auditerHtml += ' </div>';
                        $form.before(auditerHtml);
                        $('#' + _item.nodeId).lrselect({
                            data: _item.auditors,
                            id: 'auditorId',
                            text: 'auditorName'
                        });
                    }
                });
            }
        });
    };

    function initScheme() {
        // 初始化工作流节点历史处理信息
        var nodeInfoes = {};
        $.each(flowHistory, function (id, item) {
            nodeInfoes[item.nodeId] = nodeInfoes[item.nodeId] || [];
            nodeInfoes[item.nodeId].push(item);
        });
        var strcurrentIds = String(currentIds);
        // 初始化节点状态
        for (var i = 0, l = flowScheme.nodes.length; i < l; i++) {
            var node = flowScheme.nodes[i];
            node.state = '3';
            if (!!nodeInfoes[node.id]) {
                node.history = nodeInfoes[node.id];
                if (nodeInfoes[node.id][0].result == 1) {
                    node.state = '1';
                } else {
                    node.state = '2';
                }
            }
            if (currentNode.id == node.id) {
                node.state = '4';
            }

            if (strcurrentIds.indexOf(node.id) > -1) {
                var isNextNode = true;
                $.each(flowHistory, function (id, item) {
                    if (item.nodeId == node.id) {
                        isNextNode = false;
                    }
                });
                if (isNextNode == true) {
                    node.state = '0';
                }
            }


            //if (type != '101') {
            //    if (currentNode.id == node.id) {
            //        node.state = '4';
            //    }
            //}
        }
        $('#flow').lrworkflowSet('set', {data: flowScheme});
    }

    function initTimeLine(flowHistory) {
        var nodelist = [];

        var point = getCurrentNodeInfo();
        if (point) {
            nodelist.push(point);
        }

        for (var i = 0, l = flowHistory.length; i < l; i++) {
            var item = flowHistory[i];

            var content = '';

            if (item.taskType == 1) {
                if (!!item.previousId && item.result == 1) {
                    content += '【通过】';
                } else if (!!item.previousId) {
                    content += '【不通过】';
                }
            }
            if (item.description) {
                content += item.description;
            }

            var point = {
                title: item.nodeName,
                people: item.createUsername + ':',
                content: content,
                time: item.createTime
            };
            nodelist.push(point);
        }


        $('#auditinfo').lrtimeline(nodelist);
    }

    function getCurrentNodeInfo() {
        // 当前节点处理人信息
        var strcurrentIds = String(currentIds);
        var nameList = [];
        var currentNodeTitle = "";
        // 初始化节点状态
        for (var i = 0, l = flowScheme.nodes.length; i < l; i++) {
            var node = flowScheme.nodes[i];
            if (strcurrentIds.indexOf(node.id) > -1) {
                var flag = 1;
                for (var x = 0, t = flowHistory.length; x < t; x++) {
                    if (flowHistory[x].nodeId == node.id) {
                        flag = 0;
                    }
                }

                if (flag == 1) {
                    if (currentNodeTitle == "") {
                        currentNodeTitle += node.name;
                    } else {
                        currentNodeTitle += "," + node.name;
                    }

                    if (!!node.auditors && node.auditors.length > 0) {
                        $.each(node.auditors, function (_jindex, _jitem) {
                            var name = _jitem.auditorName;
                            var typeStr = "";
                            switch (_jitem.type) {
                                case "1":
                                    typeStr = "『岗位』";
                                    break;
                                case "2":
                                    typeStr = "『角色』";
                                    break;
                                case "3":
                                    typeStr = "";
                                    break;

                            }
                            nameList.push(name + typeStr);
                        });
                    }
                }
            }
        }
        if (nameList.length > 0) {
            var point = {
                title: currentNodeTitle + "【正在处理节点】",
                people: String(nameList),
                content: '：需要其审核',
                time: "当前"
            };
            return point;
        }
    }

    page.init();
}